package com.xc.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.xc.ucenter.mapper.XcMenuMapper;
import com.xc.ucenter.model.dto.AuthParamsDto;
import com.xc.ucenter.model.dto.XcUserExt;
import com.xc.ucenter.model.po.XcMenu;
import com.xc.ucenter.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    XcMenuMapper xcMenuMapper;

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * @param s 根据账号查询用户信息
     * @param s 账号
     * @return org.springframework.security.core.userdetails.UserDetails
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 将传入的json转成AuthParamsDto对象
        AuthParamsDto authParamsDto = null;
        try {
            authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        } catch (Exception e) {
            throw new RuntimeException("请求认证参数不符合要求");
        }

        // 认证类型，有password, wx ...
        String authType = authParamsDto.getAuthType();

        // 根据认证类型从Spring容器取出指定的bean
        String beanName = authType + "_authservice";
        AuthService authService = applicationContext.getBean(beanName, AuthService.class);

        // 调用统一execute方法完成认证
        XcUserExt xcUserExt = authService.execute(authParamsDto);

        // 封装xcUserExt用户信息为UserDetails
        UserDetails userPrincipal = getUserPrincipal(xcUserExt);

        return userPrincipal;
    }

    /**
     * @param user 用户id，主键
     * @description 查询用户信息
     */
    public UserDetails getUserPrincipal(XcUserExt user) {

        // 从数据库中取出正确的密码，封装成UserDetails对象发给spring security框架进行密码比对
        String password = user.getPassword();
        // 用户权限，如果不加报Cannot pass a null GrantedAuthority collection
        String[] authorities = {"test"};
        // 根据用户id查询用户的权限
        List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(user.getId());
        if (xcMenus.size() > 0) {
            List<String> permissions = new ArrayList<>();
            xcMenus.forEach(m -> {
                // 拿到了用户拥有的权限标识符
                permissions.add(m.getCode());
            });
            // 将permissions转成数组
            authorities = permissions.toArray(new String[0]);
        }

        user.setPassword(null);
        // 将user转成json格式，用于SecurityUtil解析扩展用户信息
        String userJson = JSON.toJSONString(user);
        // 创建UserDetails对象,权限信息待实现授权功能时再向UserDetail中加入
        UserDetails userDetails = User.withUsername(userJson).password(password).authorities(authorities).build();

        return userDetails;
    }

}